package com.distribute.captcha;

import java.io.ByteArrayOutputStream;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CodeController {
	
	private Logger log = LoggerFactory.getLogger(CodeController.class);
	
	@Autowired
	private ImageCodeGenerator imageCodeGenerator;
	
	public static String SESSION_IMAGE_CODE = "session_code";
	
	// 图片转base64编码
	@RequestMapping("/getCode")
	public String createCode(HttpServletRequest request,
			@RequestParam(value = "width", required = false, defaultValue="67")Integer width,
			@RequestParam(value = "height", required = false, defaultValue="23")Integer height,
			HttpServletResponse response,
			HttpSession session)
			throws Exception {
		ImageCode generate = imageCodeGenerator.generate(width, height);
		ValidateCode code = new ValidateCode(generate.getCode(), generate.getExpireTime());
		request.getSession().setAttribute(SESSION_IMAGE_CODE, code); // 实际存储位置为redis，值为序列化后的
		HttpSession session2222 = request.getSession();
		ValidateCode code2 = (ValidateCode)request.getSession().getAttribute(SESSION_IMAGE_CODE);
		log.info(generate.getCode());
		
		ByteArrayOutputStream  bs = new ByteArrayOutputStream();
        ImageIO.write(generate.getImage(), "jpg", bs);//将绘制得图片输出到流  
        String imgstr = Base64.encodeBase64String(bs.toByteArray());
        return imgstr;
	}
	
	// 流对象输出
	@RequestMapping("/getCode2")
	public void createCode2(HttpServletRequest request,
			@RequestParam(value = "width", required = false, defaultValue="67")Integer width,
			@RequestParam(value = "height", required = false, defaultValue="23")Integer height,
			HttpServletResponse response,
			HttpSession session)
			throws Exception {
		ImageCode generate = imageCodeGenerator.generate(width, height);
		ValidateCode code = new ValidateCode(generate.getCode(), generate.getExpireTime());
		request.getSession().setAttribute(SESSION_IMAGE_CODE, code);
		HttpSession session2222 = request.getSession();
		ValidateCode code2 = (ValidateCode)request.getSession().getAttribute(SESSION_IMAGE_CODE);
		log.info(generate.getCode());
		ImageIO.write(generate.getImage(), "jpg", response.getOutputStream());
		
	}
}
